<?php
	class File{

		protected $errorMessage 		= "Invalid File Extension.";
		protected $filePath 			= "_docs/files/";
		protected $fileFormat 			= array(1=>'csv',2=>'doc',3=>'txt',4=>'pdf');
		protected $fileFullDirectory 	= ""; 	// directory where file is stored excluding $filePath

		public function getExtension($str){
			$i = strrpos($str,".");
			if(!$i){return "";}
			$l 	 = strlen($str) - $i;
			$ext = substr($str,$i+1,$l);
			return $ext;
		}
	
		public function getMimeTypes($filename){
		
			$extension = strtolower($this->getExtension($filename));
			switch($extension){
				case 'doc' 	:   $mimeType = 'application/msword';
								break;
				case 'csv'	:   $mimeType = 'text/csv';
								break;
				case 'txt' 	:   $mimeType = 'text/plain';
								break;
				case 'pdf' 	:   $mimeType = 'application/pdf';
								break;
				default		:	$mimeType = 'application/octet-stream';
								break;
			}	
			return $mimeType;
		}
		
		public function uploadFile($file,$userName,$userID){
		
			$filepath = $file['name'];
			if($filepath){
			
				$filename  = stripslashes($filepath);
				$extension = strtolower($this->getExtension($filename));
				
				$arrsearch = array_search($extension,$this->fileFormat);
				if(empty($arrsearch)){
					echo $this->errorMessage;
				}
				else{
					$new_name 		= $userName."_".$userID."_".time();
					$new_filename 	= $new_name.".".$extension;
					$new_filepath 	= $this->filePath.$new_filename;
					$copied 		= copy($file['tmp_name'], $new_filepath);
				
					if($copied){
						return $new_filename;
					}
				}
			}
		}
		
		public function downloadFile($filename){
		
			header("Content-Type: 	".$this->getMimeTypes($filename));
			header("Content-Disposition: filename=".$filename);

			if($fp = fopen($this->fileFullDirectory.$this->filePath, "r")) {
				while(!feof($fp)) {
					echo  fgets($fp, 4096);
				}
				fclose($fp);
			}
		}
		
	}
?>